var categoryId = document.getElementById("categotyId");
var productId = document.getElementById("productId");

var xhr;
categoryId.onchange = getProductIdList;

var supplierId = document.getElementById("supplierId");
var supperError = document.getElementById("supperError");

supplierId.onblur = IsRight;
supplierId.oninput = changePass;

function IsRight(){
    var n = Math.floor(Number(supplierId.value));

    if(!(n !== Infinity && String(n) === supplierId.value && n >= 0)){
        supperError.innerText="请输入整数";
        supperError.setAttribute("class","ErrorMessage");
    }

}

function  changePass(){
    supperError.innerText = "";
}

function getProductIdList(){

    //类似引用
    var selectOptions = productId.options;
    var optionLength = selectOptions.length;
    for(var i=0;i < optionLength;i++)
    {
        productId.removeChild(selectOptions[0]);
    }
    xhr = new XMLHttpRequest();
    xhr.onreadystatechange = processGetProductIdList;
    xhr.open("GET","/catalog/getProductIdList?categoryId="+categoryId.value,true);
    xhr.send(null);
}

function processGetProductIdList(){
    if(xhr.readyState == 4){
        if(xhr.status == 200){
            var str = xhr.responseText;
            var array = str.split(",");

            console.info(array.length);

            //JS中采用分隔如果结尾是分隔符的话数组数量比JAVA中得到的数量多一个
            //这里减一是因为后台传过来的字符串后面跟上了表示ItemId编号的字符串.

            var length = array.length;
            for(var i = 0;i < length-1;i++){
                var opt = document.createElement("option");
                opt.value=array[i];
                //没有这个的话用户没有办法看到值
                opt.innerText = array[i];
                productId.appendChild(opt);
            }

            var ItemId = document.getElementById("ItemId");
            ItemId.value = array[length-1];
        }
    }
}

$(document).ready(function () {
    $("#ItemSubmit").submit(function () {
        if(categoryId.value == ""){
            alert("请选择宠物类别");
            categoryId.focus();
            return false;
        }else if(supperError.innerText != ""){
            alert("请输入整数");
            supplierId.focus();
            return false;
        }
        return true;
    })
})
